<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天接口测试</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#6B7280',
                        dark: '#1F2937',
                        light: '#F3F4F6'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                scrollbar-width: none;
                -ms-overflow-style: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .transition-height {
                transition: max-height 0.3s ease;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-4 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-comments-o text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-dark">AI聊天接口测试平台</h1>
            </div>
            <div class="hidden md:flex items-center space-x-4">
                <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-moon-o text-neutral"></i>
                </button>
                <button id="helpButton" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-question-circle text-neutral"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <!-- 介绍卡片 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6 border border-gray-100">
            <h2 class="text-lg font-semibold text-dark mb-3">接口说明</h2>
            <p class="text-neutral text-sm mb-4">本页面用于测试AI聊天服务的同步和流式接口。您可以输入问题，选择接口类型，然后查看AI的响应。</p>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div class="bg-blue-50 p-3 rounded-lg border border-blue-100">
                    <div class="flex items-start space-x-2">
                        <i class="fa fa-exchange text-primary mt-0.5"></i>
                        <div>
                            <p class="font-medium text-primary">同步接口</p>
                            <p class="text-neutral mt-1">一次性返回完整的AI响应，适合简短对话</p>
                            <p class="text-xs text-gray-400 mt-1">POST /api/chat/sync</p>
                        </div>
                    </div>
                </div>
                <div class="bg-green-50 p-3 rounded-lg border border-green-100">
                    <div class="flex items-start space-x-2">
                        <i class="fa fa-refresh text-secondary mt-0.5"></i>
                        <div>
                            <p class="font-medium text-secondary">流式接口</p>
                            <p class="text-neutral mt-1">逐字返回AI响应，提供更流畅的用户体验</p>
                            <p class="text-xs text-gray-400 mt-1">POST /api/chat/stream</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 聊天界面容器 -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
            <!-- 左侧面板 - 聊天历史 -->
            <div class="lg:col-span-3 hidden lg:block">
                <div class="bg-white rounded-xl shadow-md h-full border border-gray-100 flex flex-col">
                    <div class="p-4 border-b border-gray-100">
                        <h3 class="font-semibold text-dark">聊天历史</h3>
                    </div>
                    <div class="flex-grow overflow-y-auto scrollbar-hide p-2" id="chatHistory">
                        <div class="text-center text-sm text-gray-400 py-8">
                            暂无聊天记录
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧面板 - 聊天界面 -->
            <div class="lg:col-span-9">
                <div class="bg-white rounded-xl shadow-md h-full border border-gray-100 flex flex-col">
                    <!-- 聊天头部 -->
                    <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                        <h3 class="font-semibold text-dark">AI助手</h3>
                        <div class="flex items-center space-x-2">
                            <button id="clearChat" class="text-xs px-3 py-1 rounded-full border border-gray-200 hover:bg-gray-50 transition-colors">
                                <i class="fa fa-trash-o mr-1"></i> 清空
                            </button>
                            <span class="h-2 w-2 rounded-full bg-green-500 animate-pulse"></span>
                        </div>
                    </div>

                    <!-- 聊天内容区域 -->
                    <div class="flex-grow overflow-y-auto p-4 space-y-4" id="chatContainer">
                        <!-- 欢迎消息 -->
                        <div class="flex items-start space-x-3">
                            <div class="bg-primary text-white rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                                <i class="fa fa-robot"></i>
                            </div>
                            <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 max-w-[80%] shadow-sm">
                                <p class="text-sm text-neutral">你好！我是AI助手，有什么我可以帮助你的吗？请在下方输入问题，选择接口类型，然后点击发送按钮。</p>
                            </div>
                        </div>
                    </div>

                    <!-- 聊天输入区域 -->
                    <div class="p-4 border-t border-gray-100">
                        <!-- 接口选择 -->
                        <div class="flex items-center space-x-4 mb-3">
                            <label class="inline-flex items-center space-x-2 cursor-pointer">
                                <input type="radio" name="apiType" value="sync" class="form-radio text-primary focus:ring-primary" checked>
                                <span class="text-sm text-neutral">同步接口</span>
                            </label>
                            <label class="inline-flex items-center space-x-2 cursor-pointer">
                                <input type="radio" name="apiType" value="stream" class="form-radio text-primary focus:ring-primary">
                                <span class="text-sm text-neutral">流式接口</span>
                            </label>
                        </div>

                        <!-- 输入框和发送按钮 -->
                        <div class="flex items-end space-x-2">
                            <textarea 
                                id="messageInput" 
                                class="flex-grow p-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors resize-none min-h-[80px] max-h-[120px]"
                                placeholder="请输入您的问题..."
                            ></textarea>
                            <button 
                                id="sendButton" 
                                class="bg-primary hover:bg-primary/90 text-white p-3 rounded-lg transition-colors flex-shrink-0"
                            >
                                <i class="fa fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 底部信息 -->
    <footer class="bg-white border-t border-gray-100 py-4">
        <div class="container mx-auto px-4 text-center text-sm text-neutral">
            <p>AI聊天接口测试平台 © 2024</p>
        </div>
    </footer>

    <!-- 帮助模态框 -->
    <div id="helpModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center">
        <div class="bg-white rounded-xl shadow-lg p-6 max-w-lg w-full mx-4">
            <div class="flex justify-between items-center mb-4">
                <h3 class="font-semibold text-lg text-dark">使用帮助</h3>
                <button id="closeHelpModal" class="text-neutral hover:text-dark transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="space-y-3 text-sm text-neutral">
                <p>1. 在输入框中输入您的问题</p>
                <p>2. 选择要使用的接口类型（同步接口或流式接口）</p>
                <p>3. 点击发送按钮或按Enter键发送消息</p>
                <p>4. 等待AI的响应显示在聊天窗口中</p>
                <p class="text-xs text-gray-400 mt-4">注意：接口调用可能会有延迟，请耐心等待。如果长时间没有响应，请检查网络连接并刷新页面重试。</p>
            </div>
        </div>
    </div>

    <script>
        // 元素引用
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const chatContainer = document.getElementById('chatContainer');
        const chatHistory = document.getElementById('chatHistory');
        const clearChatButton = document.getElementById('clearChat');
        const helpButton = document.getElementById('helpButton');
        const helpModal = document.getElementById('helpModal');
        const closeHelpModal = document.getElementById('closeHelpModal');
        const themeToggle = document.getElementById('themeToggle');
        const apiTypeRadios = document.querySelectorAll('input[name="apiType"]');
        
        // 存储当前选中的接口类型
        let currentApiType = 'sync';
        
        // 聊天记录
        let chatLog = [];
        
        // 初始化
        function init() {
            // 绑定事件监听器
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keydown', handleKeyDown);
            clearChatButton.addEventListener('click', clearChat);
            helpButton.addEventListener('click', () => helpModal.classList.remove('hidden'));
            closeHelpModal.addEventListener('click', () => helpModal.classList.add('hidden'));
            
            // 点击模态框背景关闭
            helpModal.addEventListener('click', (e) => {
                if (e.target === helpModal) helpModal.classList.add('hidden');
            });
            
            // 监听接口类型变化
            apiTypeRadios.forEach(radio => {
                radio.addEventListener('change', (e) => {
                    currentApiType = e.target.value;
                });
            });
            
            // 自动滚动到底部
            scrollToBottom();
        }
        
        // 处理键盘事件
        function handleKeyDown(e) {
            // Ctrl + Enter 发送消息
            if (e.ctrlKey && e.key === 'Enter') {
                sendMessage();
            }
        }
        
        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            
            if (!message) {
                showNotification('请输入问题内容', 'error');
                return;
            }
            
            // 添加用户消息到聊天界面
            addMessageToChat('user', message);
            
            // 清空输入框
            messageInput.value = '';
            
            // 禁用发送按钮
            sendButton.disabled = true;
            sendButton.classList.add('opacity-50');
            
            // 添加AI正在输入的状态
            const typingIndicator = addTypingIndicator();
            
            // 根据选择的接口类型调用不同的API
            if (currentApiType === 'sync') {
                callSyncApi(message, typingIndicator);
            } else {
                callStreamApi(message, typingIndicator);
            }
        }
        
        // 调用同步API
        function callSyncApi(message, typingIndicator) {
            // 记录开始时间
            const startTime = new Date().getTime();
            
            fetch('/api/chat/sync', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 记录结束时间并计算响应时间
                const endTime = new Date().getTime();
                const responseTime = endTime - startTime;
                
                // 移除正在输入的状态
                removeTypingIndicator(typingIndicator);
                
                if (data.success) {
                    // 添加AI响应到聊天界面
                    addMessageToChat('ai', data.data, responseTime);
                    
                    // 添加到聊天记录
                    addToChatHistory(message, data.data, 'sync', responseTime);
                } else {
                    addMessageToChat('error', `错误: ${data.message}`);
                    showNotification(`请求失败: ${data.message}`, 'error');
                }
            })
            .catch(error => {
                // 移除正在输入的状态
                removeTypingIndicator(typingIndicator);
                
                addMessageToChat('error', `请求异常: ${error.message}`);
                showNotification(`请求异常: ${error.message}`, 'error');
                console.error('请求异常:', error);
            })
            .finally(() => {
                // 启用发送按钮
                sendButton.disabled = false;
                sendButton.classList.remove('opacity-50');
            });
        }
        
        // 调用流式API
        function callStreamApi(message, typingIndicator) {
            // 记录开始时间
            const startTime = new Date().getTime();
            
            fetch('/api/chat/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 获取可读流
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                // 移除正在输入的状态
                removeTypingIndicator(typingIndicator);
                
                // 创建AI响应元素
                const aiMessageElement = createAiMessageElement();
                const aiMessageContent = aiMessageElement.querySelector('.message-content');
                
                // 累积响应内容
                let fullResponse = '';
                
                // 读取流数据
                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            // 记录结束时间并计算响应时间
                            const endTime = new Date().getTime();
                            const responseTime = endTime - startTime;
                            
                            // 添加到聊天记录
                            addToChatHistory(message, fullResponse, 'stream', responseTime);
                            
                            // 启用发送按钮
                            sendButton.disabled = false;
                            sendButton.classList.remove('opacity-50');
                            
                            return;
                        }
                        
                        // 解码数据块
                        const chunk = decoder.decode(value, { stream: true });
                        fullResponse += chunk;
                        
                        // 更新AI响应内容
                        aiMessageContent.textContent = fullResponse;
                        
                        // 自动滚动到底部
                        scrollToBottom();
                        
                        // 继续读取下一个数据块
                        readStream();
                    }).catch(error => {
                        // 处理流读取异常
                        aiMessageContent.textContent = `流式响应异常: ${error.message}`;
                        showNotification(`流式响应异常: ${error.message}`, 'error');
                        console.error('流式响应异常:', error);
                        
                        // 启用发送按钮
                        sendButton.disabled = false;
                        sendButton.classList.remove('opacity-50');
                    });
                }
                
                // 开始读取流
                readStream();
            })
            .catch(error => {
                // 移除正在输入的状态
                removeTypingIndicator(typingIndicator);
                
                addMessageToChat('error', `请求异常: ${error.message}`);
                showNotification(`请求异常: ${error.message}`, 'error');
                console.error('请求异常:', error);
                
                // 启用发送按钮
                sendButton.disabled = false;
                sendButton.classList.remove('opacity-50');
            });
        }
        
        // 添加消息到聊天界面
        function addMessageToChat(role, content, responseTime = null) {
            let messageHtml = '';
            
            if (role === 'user') {
                messageHtml = `
                    <div class="flex items-start space-x-3 justify-end">
                        <div class="bg-primary text-white rounded-lg rounded-tr-none p-3 max-w-[80%] shadow-sm">
                            <p class="text-sm">${escapeHtml(content)}</p>
                        </div>
                        <div class="bg-gray-200 text-dark rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                            <i class="fa fa-user"></i>
                        </div>
                    </div>
                `;
            } else if (role === 'ai') {
                messageHtml = createAiMessageHtml(content, responseTime);
            } else if (role === 'error') {
                messageHtml = `
                    <div class="flex items-start space-x-3">
                        <div class="bg-red-500 text-white rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                            <i class="fa fa-exclamation-circle"></i>
                        </div>
                        <div class="bg-red-50 border border-red-100 rounded-lg rounded-tl-none p-3 max-w-[80%] shadow-sm">
                            <p class="text-sm text-red-600">${escapeHtml(content)}</p>
                        </div>
                    </div>
                `;
            }
            
            chatContainer.insertAdjacentHTML('beforeend', messageHtml);
            scrollToBottom();
        }
        
        // 创建AI消息HTML
        function createAiMessageHtml(content, responseTime) {
            const responseTimeHtml = responseTime ? 
                `<span class="text-xs text-gray-400 ml-2">${responseTime}ms</span>` : '';
            
            return `
                <div class="flex items-start space-x-3">
                    <div class="bg-primary text-white rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                        <i class="fa fa-robot"></i>
                    </div>
                    <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 max-w-[80%] shadow-sm">
                        <p class="text-sm text-neutral">${escapeHtml(content)}</p>
                        ${responseTimeHtml}
                    </div>
                </div>
            `;
        }
        
        // 创建AI消息元素
        function createAiMessageElement() {
            const messageElement = document.createElement('div');
            messageElement.className = 'flex items-start space-x-3';
            messageElement.innerHTML = `
                <div class="bg-primary text-white rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 max-w-[80%] shadow-sm">
                    <p class="text-sm text-neutral message-content"></p>
                </div>
            `;
            
            chatContainer.appendChild(messageElement);
            scrollToBottom();
            
            return messageElement;
        }
        
        // 添加正在输入的状态
        function addTypingIndicator() {
            const typingElement = document.createElement('div');
            typingElement.className = 'flex items-start space-x-3 typing-indicator';
            typingElement.innerHTML = `
                <div class="bg-primary text-white rounded-full h-8 w-8 flex items-center justify-center flex-shrink-0">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 shadow-sm">
                    <div class="flex space-x-1">
                        <div class="h-2 w-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0ms"></div>
                        <div class="h-2 w-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 150ms"></div>
                        <div class="h-2 w-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 300ms"></div>
                    </div>
                </div>
            `;
            
            chatContainer.appendChild(typingElement);
            scrollToBottom();
            
            return typingElement;
        }
        
        // 移除正在输入的状态
        function removeTypingIndicator(typingIndicator) {
            if (typingIndicator && typingIndicator.parentNode) {
                typingIndicator.parentNode.removeChild(typingIndicator);
            }
        }
        
        // 添加到聊天记录
        function addToChatHistory(userMessage, aiResponse, apiType, responseTime) {
            const chatItem = {
                id: Date.now(),
                userMessage: userMessage,
                aiResponse: aiResponse,
                apiType: apiType,
                responseTime: responseTime,
                timestamp: new Date().toLocaleString()
            };
            
            chatLog.unshift(chatItem);
            
            // 限制聊天记录数量
            if (chatLog.length > 20) {
                chatLog.pop();
            }
            
            // 更新聊天历史界面
            updateChatHistory();
        }
        
        // 更新聊天历史界面
        function updateChatHistory() {
            if (chatLog.length === 0) {
                chatHistory.innerHTML = `
                    <div class="text-center text-sm text-gray-400 py-8">
                        暂无聊天记录
                    </div>
                `;
                return;
            }
            
            let historyHtml = '';
            
            chatLog.forEach(chat => {
                const apiTypeIcon = chat.apiType === 'sync' ? 
                    '<i class="fa fa-exchange text-primary mr-1"></i>' : 
                    '<i class="fa fa-refresh text-secondary mr-1"></i>';
                
                historyHtml += `
                    <div class="p-2 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer chat-history-item" data-id="${chat.id}">
                        <div class="flex items-center justify-between mb-1">
                            <div class="flex items-center space-x-1">
                                ${apiTypeIcon}
                                <span class="text-xs text-neutral">${chat.timestamp}</span>
                            </div>
                            <span class="text-xs text-gray-400">${chat.responseTime}ms</span>
                        </div>
                        <p class="text-sm text-dark line-clamp-2">${escapeHtml(chat.userMessage)}</p>
                    </div>
                `;
            });
            
            chatHistory.innerHTML = historyHtml;
            
            // 绑定聊天历史项点击事件
            document.querySelectorAll('.chat-history-item').forEach(item => {
                item.addEventListener('click', () => {
                    const chatId = parseInt(item.getAttribute('data-id'));
                    const chat = chatLog.find(c => c.id === chatId);
                    if (chat) {
                        // 这里可以添加显示历史聊天详情的逻辑
                        showNotification('历史聊天记录', 'info');
                    }
                });
            });
        }
        
        // 清空聊天
        function clearChat() {
            // 保留欢迎消息
            const welcomeMessage = chatContainer.children[0].outerHTML;
            chatContainer.innerHTML = welcomeMessage;
            
            // 清空聊天记录
            chatLog = [];
            updateChatHistory();
            
            showNotification('聊天记录已清空', 'success');
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            // 创建通知元素
            const notification = document.createElement('div');
            
            // 设置通知样式
            let bgColor = 'bg-blue-500';
            let icon = 'fa-info-circle';
            
            if (type === 'success') {
                bgColor = 'bg-green-500';
                icon = 'fa-check-circle';
            } else if (type === 'error') {
                bgColor = 'bg-red-500';
                icon = 'fa-exclamation-circle';
            }
            
            notification.className = `fixed bottom-4 right-4 ${bgColor} text-white px-4 py-2 rounded-lg shadow-lg flex items-center space-x-2 z-50 transform translate-y-10 opacity-0 transition-all duration-300`;
            notification.innerHTML = `
                <i class="fa ${icon}"></i>
                <span>${escapeHtml(message)}</span>
            `;
            
            // 添加到文档
            document.body.appendChild(notification);
            
            // 显示通知
            setTimeout(() => {
                notification.classList.remove('translate-y-10', 'opacity-0');
            }, 10);
            
            // 自动隐藏
            setTimeout(() => {
                notification.classList.add('translate-y-10', 'opacity-0');
                
                // 移除通知元素
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
        
        // 自动滚动到底部
        function scrollToBottom() {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>